
const http = require('http')
const path = require('path')
const fs = require('fs')
const url = require('url')
const routes = require('./routes')

function routePath(req, res) {
    const pathObj = url.parse(req.url);
    console.log("pathname:", pathObj.pathname);
    const handleFun = routes[pathObj.pathname];

    if (handleFun) {
      // 匹配到路由，当做请求进行处理
      console.log("handleFun")
      if (req.method == "GET") {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Headers", "*");
        console.log("GET")
        res.end(responseData);
        return;
      } else if (req.method == "OPTIONS") {
        // 当请求的Content-Type为application/json时, 客户端会先发送一个
        // OPTIONS请求来试探服务端是否允许跨域请求, 然后再发送一个POST请求
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Headers", "*");
        console.log("OPTIONS")
        res.end("");
        return;
      }
      req.query = pathObj.query;
      console.log("pathObjQuery:",pathObj.query);
      // const body='';
      let body = [];
      req.on('data', (chunk) => {
          body.push(chunk);
      }).on('end', () => {
          body = Buffer.concat(body).toString();
          console.log("body", body);
          let jsonObj = JSON.parse(body);
          req.body = jsonObj;
          res.setHeader('Content-Type', 'text/plain');
          res.setHeader("Access-Control-Allow-Origin", "*");
          res.setHeader("Access-Control-Allow-Headers", "*");
          console.log("end")
          handleFun(req, res);
      });
    } else {   // 没有匹配到路由,当做静态文件进行处理
      res.statusCode = 404;
      res.setHeader('Content-Type', 'text/plain');
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader("Access-Control-Allow-Headers", "*");
      res.end("");
      return;
    }
}

function staticRoute(staticPath,req,res){
    const pathObj = url.parse(req.url,true)
    const filePath = path.join(staticPath, pathObj.pathname)
    fs.readFile(filePath,'binary', function(err, content){
        if(err){
          res.writeHead('404', 'Not Found')
          return res.end()
        }
        res.writeHead(200, 'Ok')
        res.write(content, 'binary')
        res.end()  
      })
}

// 如果匹配上了，就进入这个逻辑。
function parseBody(body){
    var obj = {}
    body.split('&').forEach(function(str){
      obj[str.split('=')[0]] = str.split('=')[1]
    })
    return obj
  }


// 主函数入口：
const server = http.createServer(function(req, res){
    routePath(req, res)       //处理方法
  })
module.exports = server;